/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controller;

import Connectdata.connectdatabase;
import DTO.Object.OrderClient.Order1;
import DTO.Object.OrderClient.Orders;
import DTO.Object.OrderDetail.Orderdetail1;
import DTO.Object.OrderDetail.Orderdetails;
import DTO.Object.OrderUser.Orderuser1;
import DTO.Object.OrderUser.Orderusers;
import DTO.Object.Users.UserSchema1;
import DTO.Object.Users.UserSchemas;
import Model.Order;
import Model.XMLvalidateXSD;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;
import java.math.BigInteger;
import java.sql.SQLException;
import java.util.GregorianCalendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.apache.fop.apps.Driver;
import org.apache.fop.apps.FOPException;
import org.xml.sax.InputSource;

/**
 *
 * @author annt60258
 */
public class Finshcheckout extends HttpServlet {

    private String hethang = "index.jsp";

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        String context = request.getParameter("xmlContent");

        if (session.getAttribute("username") != null && !session.getAttribute("username").equals("admin") && session.getAttribute("success").equals("success")) {
            try {
                if (context!=null&&context!="") {
                    try {
                        String realpath = getServletContext().getRealPath("/");
                        int tong = 0;
                         JAXBContext jaxb_unmar = JAXBContext.newInstance("DTO.Object.OrderClient");
                        Unmarshaller um = jaxb_unmar.createUnmarshaller();
                        Orders orderclient = (Orders)um.unmarshal(new InputSource(new StringReader(context)));



                        String username = session.getAttribute("username").toString();
                        UserSchemas userschemas = new UserSchemas();
                        UserSchema1 userschema1 = new UserSchema1();
                        connectdatabase connect = new connectdatabase();
                        connect.connect();
                        connect.connectstring("select * from UserAccount where UserName='" + username + "'");
                        if (connect.rs_connect.next()) {
                            userschema1.setUserName(username);
                            userschema1.setFullName(connect.rs_connect.getString("FullName"));
                            userschema1.setEmail(connect.rs_connect.getString("Mail"));
                            userschema1.setAddress(connect.rs_connect.getString("Address"));
                            userschema1.setPhone(connect.rs_connect.getString("Phone"));
                        }
                        userschemas.getUserSchema().add(userschema1);
                        String pathuserschema = realpath + "XML/Userxml.xml";
                        JAXBContext jaxb = JAXBContext.newInstance(userschemas.getClass());
                        Marshaller mar = jaxb.createMarshaller();
                        mar.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.FALSE);
                        mar.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
                        mar.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
                        mar.marshal(userschemas, new File(pathuserschema));
                        //finish marshall user
                        //marshall order
                        Orderusers orderusers = new Orderusers();
                        Orderuser1 orderuser1 = new Orderuser1();
                        GregorianCalendar gregorianCalendar = new GregorianCalendar();
                        DatatypeFactory datatypeFactory = DatatypeFactory.newInstance();
                        XMLGregorianCalendar now = datatypeFactory.newXMLGregorianCalendar(gregorianCalendar);
                        Order ordermodel = new Order();
                        String orderid = ordermodel.getidUser("orderID", "OrderPayment");
                        orderuser1.setOrderID(new BigInteger(orderid));
                        orderuser1.setUserName(username);
                        orderuser1.setOrderDate(now);
                        orderuser1.setOrderStatus(0);
                        orderusers.getOrderuser().add(orderuser1);
                        String realpathorder = realpath + "XML/Orderxml.xml";
                        JAXBContext jaxb_order = JAXBContext.newInstance(orderusers.getClass());
                        Marshaller mar_order = jaxb_order.createMarshaller();
                        mar_order.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
                        mar_order.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
                        mar_order.marshal(orderusers, new File(realpathorder));
                        //finish marshall order
                        //marshall order detail
                        Orderdetails orderdetails = new Orderdetails();
                        for (int i = 0; i < orderclient.getOrder().size(); i++) {
                            Order1 tmp = orderclient.getOrder().get(i);
                            Orderdetail1 orderdetail1 = new Orderdetail1();
                            orderdetail1.setOrderMother(new BigInteger(orderid));
                            orderdetail1.setProductID(tmp.getIdproduct());
                            orderdetail1.setProductName(tmp.getProductname());
                            orderdetail1.setPicture(realpath + ordermodel.getpicturepath(tmp.getIdproduct().toString()));
                            orderdetail1.setQuantity(tmp.getQuantity());
                            orderdetail1.setPrice(tmp.getPrice());
                            tong += tmp.getQuantity()*tmp.getPrice().longValue();
                                orderdetails.getOrderdetail().add(orderdetail1);


                        }
                        orderdetails.setTong(tong);
                        String realpath_orderdetail = realpath + "XML/Orderdetailxml.xml";
                        JAXBContext jaxb_orderdetail = JAXBContext.newInstance(orderdetails.getClass());
                        Marshaller mar_orderdetail = jaxb_orderdetail.createMarshaller();
                        mar_orderdetail.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
                        mar_orderdetail.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
                        mar_orderdetail.marshal(orderdetails, new File(realpath_orderdetail));
                        //finish marshall order detail
                        //validate order
                        boolean validateorder = XMLvalidateXSD.XMLvalidate(realpathorder, realpath + "schema/orderuser_old.xsd");
                        //finish validate order
                        if (validateorder) {
                            boolean validateorderdetail = XMLvalidateXSD.XMLvalidate(realpath_orderdetail, realpath + "schema/orderdetail_old.xsd");
                            if (validateorderdetail) {
                                boolean checksoluong = ordermodel.checksoluongsp(orderdetails);
                                if (!checksoluong) {
                                    String datebuy = orderuser1.getOrderDate().getYear() + "-"
                                            + orderuser1.getOrderDate().getMonth() + "-"
                                            + orderuser1.getOrderDate().getDay()+" "
                                            +orderuser1.getOrderDate().getHour()+":"
                                            +orderuser1.getOrderDate().getMinute()+":"
                                            +orderuser1.getOrderDate().getSecond();
                                    boolean flagorderinsert = ordermodel.InsertDatabaseorder(orderuser1.getUserName(), datebuy);
                                    if (flagorderinsert) {
                                        //insert orderdetail and update Product
                                        ordermodel.InsertOrderDetailandUpdateProduct(orderdetails);
                                        //transform xsl
                                        TransformerFactory tFactory = TransformerFactory.newInstance();
                                        Transformer transformer = tFactory.newTransformer(new StreamSource(realpath + "xsl/PDF_FO.xsl"));
                                        transformer.transform(new StreamSource(realpath + "XML/Userxml.xml"), new StreamResult(new FileOutputStream(realpath + "WEB-INF/Furniture.fo")));
                                        //ket thuc transform xsl
                                        //viet ra pdf
                                        String path = getServletContext().getRealPath("/");
                                        String fileName = path + "WEB-INF/Furniture.fo";
                                        File file = new File(fileName);
                                        FileInputStream input = new FileInputStream(file);
                                        ByteArrayOutputStream output = new ByteArrayOutputStream();
                                        response.setContentType("application/pdf");
                                        Driver driver = new Driver(new org.xml.sax.InputSource(input), output);
                                        //org.apache.avalon.framework.logger.Logger log1 = new org.apache.avalon.framework.logger.ConsoleLogger(org.apache.avalon.framework.logger.ConsoleLogger.LEVEL_WARN);
                                        driver.setRenderer(Driver.RENDER_PDF);
                                        driver.run();
                                        byte[] content = output.toByteArray();
                                        response.setContentLength(content.length);
                                        response.getOutputStream().write(content);
                                        response.getOutputStream().flush();
                                        //ket thuc viet pdf
                                    }

                                    //hoan thanh huy session
                                    //hoan thanh huy session
                                } else {
                                    session.setAttribute("hethang", "hethang");
                                    session.setAttribute("productfail", ordermodel.productfail);
                                    session.setAttribute("numproductfail", ordermodel.numproductfail);
                                    RequestDispatcher rqd = request.getRequestDispatcher(hethang);
                                    rqd.forward(request, response);
                                }
                            } else {
                                session.setAttribute("validateorderdetail", "orderdetailfail");
                                RequestDispatcher rqd = request.getRequestDispatcher(hethang);
                                rqd.forward(request, response);
                            }
                        } else {
                            session.setAttribute("validateorder", "orderfail");
                            RequestDispatcher rqd = request.getRequestDispatcher(hethang);
                            rqd.forward(request, response);
                        }
                    } catch (FOPException ex) {
                        Logger.getLogger(Finshcheckout.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (TransformerException ex) {
                        Logger.getLogger(Finshcheckout.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (DatatypeConfigurationException ex) {
                        Logger.getLogger(Finshcheckout.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (JAXBException ex) {
                        Logger.getLogger(Finshcheckout.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (SQLException ex) {
                        Logger.getLogger(Finshcheckout.class.getName()).log(Level.SEVERE, null, ex);
                    }
                } else {
                }
                //viet ra pdf
                String path = getServletContext().getRealPath("/");
                String fileName = path + "WEB-INF/Furniture.fo";
                File file = new File(fileName);
                FileInputStream input = new FileInputStream(file);
                ByteArrayOutputStream output = new ByteArrayOutputStream();
                response.setContentType("application/pdf");
                Driver driver = new Driver(new org.xml.sax.InputSource(input), output);
                //org.apache.avalon.framework.logger.Logger log1 = new org.apache.avalon.framework.logger.ConsoleLogger(org.apache.avalon.framework.logger.ConsoleLogger.LEVEL_WARN);
                driver.setRenderer(Driver.RENDER_PDF);
                driver.run();
                byte[] content = output.toByteArray();
                response.setContentLength(content.length);
                response.getOutputStream().write(content);
                response.getOutputStream().flush();
                //ket thuc viet pdf
            } catch (FOPException ex) {
                Logger.getLogger(Finshcheckout.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {
            session.setAttribute("faillogin", "faillogin");
            RequestDispatcher rqd = request.getRequestDispatcher(hethang);
            rqd.forward(request, response);
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
